package server

import (
	"errors"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"sieve_admin_server_userpass/pkg/hash"
	ufile "sieve_admin_server_userpass/pkg/util/file"
	uTime "sieve_admin_server_userpass/pkg/util/time"
	"time"
)

var staticFile = filepath.Join(filepath.Dir(os.Args[0]), "../staticFile")

func UploadFiles(r *http.Request) ([]string, error) {
	form := r.MultipartForm // form变量被赋值为一个多文件的表单
	files := form.File["file"]
	list := []string{}
	for _, head := range files {
		fileName, err := UploadFile(head, "")
		if err != nil {
			return nil, err
		}
		list = append(list, fileName)
	}
	return list, nil
}

func UploadFile(head *multipart.FileHeader, dstFile string) (string, error) {
	file, err := head.Open()
	if err != nil {
		return "", err
	}
	if dstFile == "" {
		dir := uTime.FmtDate(time.Now(), "Ym") + "/"
		exist, err := ufile.PathExists(staticFile + "/" + dir)
		if err != nil {
			return "", err
		}
		if !exist {
			os.MkdirAll(staticFile+"/"+dir, os.ModePerm)
		}
		dstFile = filepath.Join(staticFile, dir, hash.MD5([]byte(time.Now().String()))+"_"+head.Filename)
	}
	fW, err := os.Create(dstFile)
	if err != nil {
		return "", errors.New("文件创建失败:" + err.Error())
	}
	defer fW.Close()
	_, err = io.Copy(fW, file)
	if err != nil {
		return "", errors.New("文件保存失败:" + err.Error())
	}
	return dstFile, nil
}
